package com.gxa.servlet.goods;

import com.alibaba.fastjson.JSON;
import com.gxa.pojo.Result;
import com.gxa.pojo.goods.Goods;
import com.gxa.service.goods.GoodsService;
import com.gxa.service.goods.impl.GoodsServiceimpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/GoodsInsertSServlet")
public class GoodsInsertSServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        GoodsService goodsService = new GoodsServiceimpl();
        request.setCharacterEncoding("utf-8");
//        //因为request.getreader（）方法只能读一次，采样下面几行代码
        BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
        StringBuilder json = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            json.append(inputStr);
        }
        String s = json.toString(); //这是将json转化为字符串的形式
        List<Goods> goods = JSON.parseArray(s, Goods.class);
        int insert = goodsService.insertgoddss(goods);
        Map<String, Object> map = new HashMap<>();
        if (insert!=0){
            map.put("Result", Result.ok("添加成功"));
        }else {
            map.put("Result",Result.error());
        }
        response.setContentType("text/json;charset=utf-8");
        String s1 = JSON.toJSONString(map);
        response.getWriter().write(s1);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
